/*
 * @Description:
 * @Autor: dongjunhua
 * @Date: 2020-12-17 12:52:35
 * @LastEditors: dongjunhua
 * @LastEditTime: 2022-04-14 10:51:17
 */
'use strict';

const path = require('path');
const defaultConfig = require('./src/config');
// const { name } = require('./package.json');

function resolve(dir) {
  return path.join(__dirname, dir);
}

// devServer
const devServer = {
  port: 3000,
  open: true,
  overlay: {
    warnings: false,
    errors: true
  },
  headers: {
    'Access-Control-Allow-Origin': '*'
  }
};

if (process.env.NODE_ENV === 'mock') {
  devServer.before = require('./mock/mock-server.js');
} else {
  devServer.proxy = {
    // detail: https://cli.vuejs.org/config/#devserver-proxy
    [process.env.VUE_APP_BASE_API]: {
      target: 'http://localhost:8001',
      changeOrigin: true,
      pathRewrite: {
        ['^' + process.env.VUE_APP_BASE_API]: ''
      }
    }
  };
}

module.exports = {
  publicPath: process.env.VUE_APP_BASE_URI,
  outputDir: 'dist',
  assetsDir: 'static',
  productionSourceMap: false,
  devServer,
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: defaultConfig.applicationName,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    performance: {
      hints: false, // close performance warning
      assetFilter: function(assetFilename) {
        // file filter
        return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
      }
    }
    // output: {
    //   library: `${name}-[name]`,
    //   libraryTarget: 'umd', // 把微应用打包成 umd 库格式
    //   jsonpFunction: `webpackJsonp_${name}`
    // }
  },
  chainWebpack(config) {
    const CompressionWebpackPlugin = require('compression-webpack-plugin');
    config.plugin('compressionWebpack').use(CompressionWebpackPlugin);
    // when use preload, it will cause runtime not found
    config.plugins.delete('preload');
    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch');
    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end();
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use()
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end();
    config.module
      .rule('js')
      .use('babel-loader')
      .options({
        presets: [['@babel/preset-env', { modules: false }]],
        cacheCompression: true
      });

    config.when(process.env.NODE_ENV === 'development', config =>
      config.devtool('cheap-source-map')
    );

    config.when(process.env.NODE_ENV !== 'development', config => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end();
      config.optimization.splitChunks({
        chunks: 'all',
        maxAsyncRequests: 5,
        maxInitialRequests: 5,
        cacheGroups: {
          config: {
            name: 'chunk-config',
            minSize: 1,
            test: /[\\/]src[\\/]config[\\/]/,
            priority: 30
          },
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          element: {
            name: 'chunk-libs-elememt', // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-plus(.*)/ // in order to adapt to cnpm
          },
          vant: {
            name: 'chunk-libs-vant', // split vant into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?vant(.*)/ // in order to adapt to cnpm
          }
        }
      });
      config.optimization.runtimeChunk('single');
    });
  }
};
